import {
  getMyCoupons,
  get_MyCouponsList
} from '../../sers/coupon/coupon';
import {
  getMyCards
} from '../../sers/hmbcard/hmbcard';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['储值卡', '优惠券', "赠送记录"],
    myCardList: [],
    myCouponList: [],
    selTabsInx: 0,
    fontColor: "#3A3030",
    spaceTag: true,
    tittop: app.globalData.tittop + 'rpx',
    lbtop: app.globalData.lbtop + 'rpx',
    isWindows: app.globalData.isWindows,
    isShowPopAuth: false,
    checked: false,
    disShowPop: false,
    getnotshared: wx.getStorageSync('get_notshared_gift'),
    isShowshare: false,
    giftData: {}
  },
  onShareAppMessage(item) {
    console.log(item)
    let data = item.target.dataset.item
    // let cunponCard = `/pages/coupon/claimCoupon/index?couponId=${this.data.myCoupon.card_no}&num=${ this.data.cardCounts}&splitIdCoupon=${this.data.splitIdCoupon.couponCode}`
    return {
      title: data.cardName,
      path: `/pages/coupon/claimCoupon/index?splitIdCoupon=${data.cardNo}&couponId=${''}&num=${data.balance}&name=${data.cardName}&url=${data.url}`,
      imageUrl: data.url,
    };
  },
  // qty 券张数
  // 取消分享
  canceGiftbtn(item) {
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    // if (user.mobile != null) {
    console.log(item.currentTarget.id)
    let data = {
      sign: 0,
      couponCode: item.currentTarget.id,
      mobile: user.mobile
    }
    this.cancelGift(data)
    let index = {
      detail: {
        index: 2
      }
    }
    this.tabsItemChange(index)
    // this.onPullDownRefresh()
  },
  // 取消分享接口
  cancelGift(data) {
    console.log('取消参数')
    console.log(data)
    wx.request({
      url: app.get_request_url("confirmSplitCoupon", "coupons"),
      method: "POST",
      data: data,
      dataType: "json",
      success: res => {
        if (res.data.code == 0) {
          console.log(res)
          wx.showToast({
            title: res.data.msg,
            duration: 1000 // 这里设置你需要的时长，单位是毫秒
          });
          this.setData({
            isShowshare: false
          })
          wx.setStorageSync('get_notshared_gift', '');
        } else {
          this.setData({
            isShowshare: false
          })
          wx.showToast({
            title: res.data.msg,
            duration: 1000 // 这里设置你需要的时长，单位是毫秒
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        app.showToast("服务器请求出错");
      }
    });
  },
  //取消分享
  cance_btn() {
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    if (user.mobile != null) {
      this.setData({
        isShowshare: false
      })
      let data = {
        sign: 0,
        couponCode: this.data.getnotshared.splitIdCoupon,
        mobile: user.mobile,
      }
      console.log('取消参数')
      console.log(data)
      this.cancelGift(data)
    }
  },
  cancelGift(data) {
    console.log('取消参数')
    console.log(data)
    wx.request({
      url: app.get_request_url("confirmSplitCoupon", "coupons"),
      method: "POST",
      data: data,
      dataType: "json",
      success: res => {
        if (res.data.code == 0) {
          console.log(res)
          wx.showToast({
            title: "操作成功！",
            duration: 1000 // 这里设置你需要的时长，单位是毫秒
          });
          wx.setStorageSync('get_notshared_gift', '');
        } else {
          wx.showToast({
            title: res.data.msg,
            duration: 1000 // 这里设置你需要的时长，单位是毫秒
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        app.showToast("服务器请求出错");
      }
    });
  },
  // 在目标页面保存时间戳
  // 在首页 onShow 中判断是否需要刷新
  onShow() {
    console.log(wx.getStorageSync('get_notshared_gift'))
    if (this.selTabsInx === 1) {
      if (this.getnotshared) {
        console.log("--------------------")
        this.setData({
          isShowshare: true
        })
        this.getnotshared = wx.getStorageSync('get_notshared_gift')
      }
    }
    const lastUpdate = wx.getStorageSync('lastUpdate');
    console.log(Date.now())
    if (lastUpdate != Date.now()) {
      this.onPullDownRefresh();
    }
  },
  // refresh(){
  //     this.setData({ userInfo: wx.getStorageSync('userInfo') });
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.loadData();
    console.log("lolooo")
    let index = options.index;
    console.log(index)
    if (index != null) {
      this.home(index);
    } else {
      this.home();
    }
  },

  home(index) {
    console.log('进去卡券页面');
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobile;
    if (user != null) {
      mobile = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobile = app.globalData.userInfo.mobile
      }
    }
    if (index != null) {
      this.setData({
        selTabsInx: index
      });
      getMyCoupons(mobile).then(myList => {
        if (myList.data.data == '') {
          this.setData({
            myCouponList: null
          });
        } else {
          var data = myList.data.data.coupons;
          for (var i = 0; i < data.length; ++i) {
            var temp = data[i].remark.replace(/\\n/g, '');
            data[i].remark = temp;
          }
          this.setData({
            myCouponList: data
          });
        }
      }).catch(error => {});
    } else {
      this.setData({
        selTabsInx: 0
      });
      getMyCards(mobile).then(myList => {
        this.setData({
          myCardList: myList.data.data.cards
        });
      }).catch(error => {});
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // this.home();
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobile;
    if (user != null) {
      mobile = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobile = app.globalData.userInfo.mobile
      }
    }
    if (this.data.selTabsInx == 0) {
      getMyCards(mobile).then(myList => {
        if (myList.data.data == '') {
          this.setData({
            myCardList: null
          });
        } else {
          this.setData({
            myCardList: myList.data.data.cards
          });
        }
      }).catch(error => {
        console.log(error);
      });
    } else if (this.data.selTabsInx == 1) {
      getMyCoupons(mobile).then(myList => {
        if (myList.data.data == '') {
          this.setData({
            myCouponList: null
          });
        } else {
          for (let i in myList.data.data.coupons) {
            let temp = myList.data.data.coupons[i]
            temp.startTime_ = temp.validity.split('~')[0].substr(0, 11)
            temp.entTime_ = temp.validity.split('~')[1].substr(0, 11)
          }
          this.setData({
            myCouponList: myList.data.data.coupons
          });
        }
      }).catch(error => {});
    } else {
      get_MyCouponsList(mobile).then(myList => {
        console.log(myList)
        let data = myList.data.data
        if (data == '') {
          this.setData({
            myCouponList: null
          });
        } else {
          for (let i in data) {
            let temp = data[i]
            temp.startTime_ = temp.validity.split('~')[0].substr(0, 11)
            temp.entTime_ = temp.validity.split('~')[1].substr(0, 11)
          }
          console.log(data)
          this.setData({
            myCouponList: data
          });
        }
      }).catch(error => {
        console.log(error);
      });
    }
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */

  tabsItemChange(e) {
    this.setData({
      myCouponList: []
    });
    console.log(e.detail.index);
    let sInx = e.detail.index;
    this.setData({
      selTabsInx: sInx,
      // isShowshare: true
    });
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobile;
    if (user != null) {
      mobile = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobile = app.globalData.userInfo.mobile
      }
    }
    if (this.selTabsInx === 1) {
      if (this.getnotshared) {
        this.getnotshared = wx.getStorageSync('get_notshared_gift')
      }
    }
    if (sInx === 0) {
      getMyCards(mobile).then(myList => {
        this.setData({
          myCardList: myList.data.data.cards,
          isShowshare: false
        });
      }).catch(error => {
        console.log(error);
      });
    } else if (sInx === 1) {
      this.getnotshared = wx.getStorageSync('get_notshared_gift')
      console.log(this.getnotshared)
      if (this.getnotshared !== '') {
        this.setData({
          isShowshare: true
        })
      }
      getMyCoupons(mobile).then(myList => {
        for (let i in myList.data.data.coupons) {
          let temp = myList.data.data.coupons[i]
          temp.startTime_ = temp.validity.split('~')[0].substr(5, 5)
          temp.entTime_ = temp.validity.split('~')[1].substr(0, 11)
        }
        this.setData({
          myCouponList: myList.data.data.coupons
        });
      }).catch(error => {
        console.log(error);
      });
    } else {
      get_MyCouponsList(mobile).then(myList => {
        console.log(myList)
        let data = myList.data.data
        if (data == '') {
          this.setData({
            myCouponList: null
          });
        } else {
          for (let i in data) {
            let temp = data[i]
            temp.startTime_ = temp.validity.split('~')[0].substr(0, 11)
            temp.entTime_ = temp.validity.split('~')[1].substr(0, 11)
          }
          console.log(data)
          this.setData({
            myCouponList: data
          });
        }
      }).catch(error => {
        console.log(error);
      });
    }
  },
  toBindCard(e) {
    console.log(e);
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    console.log(user)
    if (user == null) {
      this.setData({
        isShowPopAuth: true
      })
    } else {
      wx.navigateTo({
        url: '/pages/card/index',
      });
    }
  },

  toCardDetail(e) {
    console.log(e);
    console.log(e.currentTarget.id);
    wx.navigateTo({
      url: '/pages/card/carddetail/index?cardNo=' + e.currentTarget.id,
    });
  },
  // 延期刷新
  getloadTab() {
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobile;
    if (user != null) {
      mobile = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobile = app.globalData.userInfo.mobile
      }
    }
    // 判断当前是哪个Tab，然后调用对应的数据获取函数
    if (this.data.selTabsInx == 0) {
      // 当前是储值卡Tab
      getMyCards(mobile).then(myList => {
        if (myList.data.data == '') {
          this.setData({
            myCardList: null
          });
        } else {
          this.setData({
            myCardList: myList.data.data.cards
          }); // 更新数据
        }
      }).catch(error => {
        console.log(error);
      });
    } else {
      // 当前是优惠券Tab
      getMyCoupons(mobile).then(myList => {
        if (myList.data.data == '') {
          this.setData({
            myCouponList: null
          });
        } else {
          this.setData({
            myCouponList: myList.data.data.coupons
          }); // 更新数据
        }
      }).catch(error => {
        console.log(error);
      });
    }
  },
  // 延期
  getMoreTime(e) {
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    console.log(user)
    if (user != null) {
      let parame = {
        coupon_code: e,
        mobile: user.mobile
      }
      console.log(parame)
      console.log("测试延期")
      wx.showModal({
        title: '确认申请', // 弹窗标题
        content: '您确定要提交申请吗？', // 弹窗内容
        confirmText: '确定', // 确认按钮文字，默认为"确定"
        cancelText: '取消', // 取消按钮文字，默认为"取消"
        success: (res) => { // 用户点击按钮后的回调函数
          if (res.confirm) {
            console.log('用户点击了确定')
            wx.request({
              url: app.get_request_url("extensionCoupon", "coupons"),
              method: "POST",
              data: parame,
              dataType: "json",
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: res_ => {
                console.log("申请延期")
                console.log(res_)
                if (res_.data.code == -1) {
                  wx.showToast({
                    icon: "none",
                    title: res_.data.msg,
                    duration: 3000,
                  });
                } else {
                  wx.showToast({
                    icon: "none",
                    title: '申请成功！',
                    duration: 3000,
                  });
                  this.getloadTab()
                  this.home()
                  let index = {
                    detail: {
                      index: 1
                    }
                  }
                  this.tabsItemChange(index)
                }
              },
              fail: (err) => {
                console.log(err)
                app.showToast("服务器请求出错");
              },
            });
          } else if (res.cancel) {
            console.log('用户点击了取消')
          }
        }
      })
    }
  },
  toShareFirend(e) {
    // console.log(e)
    wx.navigateTo({
      url: '/pages/coupon/sharedetail/index?couponCode=' + e.currentTarget.id,
    });
  },
  toGetMoreTime(e) {
    let cardStatus = e.currentTarget.dataset.item
    if (cardStatus.status == 1) {
      this.getMoreTime(e.currentTarget.id)
    }
  },
  toCouponDetail(e) {
    let cardStatus = e.currentTarget.dataset.item
    console.log(cardStatus)
    // if (cardStatus.status == 1) {
    //   // this.getMoreTime(e.currentTarget.id)
    //   // wx.showModal("券已过期!")
    //   wx.showModal({
    //     title: '温馨提示',
    //     content: '券已过期/或失效！',
    //     confirmText: '确认',
    //     showCancel: false,
    //     success: (result) => {
    //       if (result.confirm) {}
    //     }
    //   });
    // } else {
    wx.navigateTo({
      url: '/pages/coupon/coupondetail/index?couponCode=' + e.currentTarget.id,
    });
    // }
  },
  // 未登录提示
  //确认授权
  modalCancel(e) {
    console.log('进入modalCancel');
    this.setData({
      disShowPop: false
    });
  },
  modalConfirm(e) {
    console.log('进入modalConfirm');
    this.setData({
      disShowPop: false
    });
    // this.toLogin();
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobileTemp;
    if (user != null) {
      mobileTemp = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTemp = app.globalData.userInfo.mobile
      }
    }
    if (mobileTemp == null) {
      console.log("kkkkkk")
      this.setData({
        isShowPopAuth: true
      });
      // wx.showModal({
      //   title: '温馨提示',
      //   content: '授权用户信息',
      //   confirmText: '确认',
      //   cancelText: '暂不',
      //   success: (result) => {
      //     if (result.confirm) {
      //       wx.navigateTo({
      //         url: "/pages/login/login"
      //       });
      //     }
      //   }
      // });
    }

  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  /**
   * 登录授权事件
   */
  checkedPoint(e) {
    if (this.data.checked === false) {
      this.setData({
        checked: true,
        disShowPop: false,
      });
      this.get_user_info_event();
    }
  },
  /**
   * 登录授权事件
   */
  get_user_phone_event(e) {
    if (this.data.checked === false) {
      this.setData({
        disShowPop: true
      })
    } else if (this.data.checked === true) {
      this.user_auth_phone(e.detail);
    }
    // this.user_auth_phone(e.detail);
  },
  /**
   * 登录授权事件
   */
  get_user_info_event_(e) {
    this.setData({
      checked: true,
      disShowPop: false,
    });
    this.user_auth_code(e.detail);
  },
  get_user_info_event(e) {
    if (this.data.checked === false) {
      this.setData({
        disShowPop: true,
      });
    } else if (this.data.checked === true) {
      this.user_auth_code(e.detail);
    }
  },

  // cance_btn() {
  //   this.setData({
  //     disShowPop: false
  //   })
  // },
  /**
   * 用户授权
   * auth_data  授权数据
   */
  user_auth_code(auth_data) {
    //console.log("user_auth_code");
    if ((auth_data.encryptedData || null) != null && (auth_data.iv || null) != null) {
      console.log("aaaa")
      app.user_auth_login(this, 'user_auth_back_event', auth_data);
    } else {
      app.showToast("授权失败");
    }
  },

  /**
   * 授权返回事件
   */
  user_auth_back_event() {
    //console.log("user_auth_back_event");
    var user = app.get_user_cache_info();
    this.setData({
      user: user || null
    });
    // wx.showToast({
    //   icon: "none",
    //   title: '请继续点击获取手机号',
    // });
    //  this.setData({
    //     disShowUserPop: true,
    // })
    // 2. 获取用户信息成功后，自动触发获取手机号的隐藏按钮
    const phoneButton = this.selectComponent("#hiddenPhoneButton");
    console.log(phoneButton)
    console.log(phoneButton)
    if (phoneButton) {
      phoneButton.click(); // 此举会触发手机号授权弹窗
    } else {
      // this.setData({
      //     disShowUserPop: true,
      // })
      // 备用方案：如果无法直接操作组件，可以提示用户进行下一步操作
      //    wx.showModal({
      //      content: "请授权手机号以完成登录",
      //      success(res) {
      //        if (res.confirm) {
      //          // 这里可以引导用户点击一个实际显示的手机号授权按钮
      //        }
      //      },
      //    });
    }

    if (app.user_is_need_login(user) == false) {
      //  wx.navigateBack();
    }
  },




  /**
   * 用户授权
   * auth_data  授权数据
   */
  user_auth_phone(auth_data) {
    console.log(this.data.checked)
    console.log("user_auth_phone")
    if ((auth_data.encryptedData || null) != null && (auth_data.iv || null) != null) {
      app.user_auth_login_getPhone(this, 'user_auth_phone_back_event', auth_data);
    } else {
      app.showToast("手机授权失败");
    }
  },

  /**
   * 授权返回事件
   */
  user_auth_phone_back_event() {
    console.log("user_auth_phone_back_event");
    var user = app.get_user_cache_info();
    // var rcode = wx.getStorageSync("index_rcode");
    var rcode = app.globalData.rcode;
    console.log('rcode')
    console.log(rcode)
    if (rcode == null || rcode == '') {
      rcode = '';
    }
    this.setData({
      user: user || null,
      mobile: user.mobile,
      disShowPop: false
    });
    app.mobile = user.mobile;
    // if (app.user_mobile_check(user) == false) {
    // wx.navigateBack();
    // wx.navigateBack({
    //   success: res => {
    //     let pages = getCurrentPages();
    //     let prevPage = pages[pages.length - 1];      // 上一个页面的对象
    //     // 当然, 也可以通过setData设置那个页面的其他数据
    //     prevPage.onLoad();    // 触发上一个页面的onLoad生命周期函数
    //   }
    // });
    // }
    wx.request({
      url: app.get_request_url("savemember", "user"),
      method: "POST",
      data: {
        'memberName': '',
        'memberSex': '',
        'mobile': user.mobile,
        'address': '',
        'memberId': '',
        'rcode': rcode,
      },
      dataType: "json",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        var data = res.data.data;
        app.globalData.userInfo = data;
        wx.setStorageSync('cache_user_info', data);
        wx.showToast({
          icon: "none",
          title: '登录成功！',
        });
        wx.reLaunch({
          url: "/pages/index/index"
        });
        // wx.showModal({
        //   title: '提示',
        //   content: '注册/登录成功！',
        //   showCancel: false,
        //   success: function (res) {

        //     if (res.confirm) {
        //       // wx.navigateBack({
        //       //   success: res => {
        //       //     let pages = getCurrentPages();
        //       //     let prevPage = pages[pages.length - 1];      // 上一个页面的对象
        //       //     // 当然, 也可以通过setData设置那个页面的其他数据
        //       //     prevPage.onLoad();    // 触发上一个页面的onLoad生命周期函数
        //       //   }
        //       // });
        //       wx.reLaunch({
        //         url: "/pages/index/index"
        //       });
        //     }
        //   }
        // });
      },
      fail: () => {
        app.showToast("服务器请求出错");
      },
    });
  },

  get_user_phone_cancel() {

    // wx.navigateBack();
    try {
      wx.clearStorageSync();
    } catch (e) {}
    app.globalData.userInfo = null;
    this.setData({
      userInfo: null,
      isShowPopAuth: false,
      user: null,
      checked: false
    });
    // wx.reLaunch({
    //   url: '/pages/index/index?op=exithmb'
    // });
  },


})